import datetime
import json

from fastapi.encoders import jsonable_encoder
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy import ForeignKey, String, Text
from sqlalchemy.orm import Session
from sqlalchemy.orm import relationship

from core.db.database import Base
from core.db.database import get_db


class BaseModel:
    id = Column(Integer, primary_key=True, index=True)
    is_deleted = Column(Integer, comment="是否删除", server_default="0")
    created_at = Column(DateTime, default=datetime.datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment="更新时间")

    def __init__(self):
        self.__table__ = None

    def save(self, session: Session = None):
        """保存模型到数据库
        
        Args:
            session (Session, optional): 数据库会话。如果未提供，将创建新会话。
        """
        close_session = False
        if session is None:
            session = next(get_db())
            close_session = True
            
        try:
            if self.id is None:
                session.add(self)
            session.commit()
            result = self.to_dict()
            return result
        finally:
            if close_session:
                session.close()

    def destroy(self, session: Session = None):
        """从数据库中删除此模型
        
        Args:
            session (Session, optional): 数据库会话。如果未提供，将创建新会话。
        """
        close_session = False
        if session is None:
            session = next(get_db())
            close_session = True
            
        try:
            session.delete(self)
            session.commit()
        finally:
            if close_session:
                session.close()

    def to_dict(self):
        # 获取对象映射
        data = {column.name: getattr(self, column.name) for column in self.__table__.columns}
        if type(data.get('create_at')) is datetime.datetime:
            data['create_at'] = data['create_at'].strftime("%Y-%m-%d %H:%M:%S")
            data['update_at'] = data['update_at'].strftime("%Y-%m-%d %H:%M:%S")
        return data

    class Config:
        orm_mode = True


class User(Base, BaseModel):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    userName = Column(String(32), comment="账号")
    userPwd = Column(String(128), comment="密码")
    nickName = Column(String(128), comment="昵称")
    userId = Column(String(32), comment="微信号")
    photo = Column(String(128), comment="头像")
    signature = Column(String(128), comment="签名")
    area = Column(String(32), comment="所在区域")
    sex = Column(String(32), comment="性别")
    mobile = Column(String(32), comment="手机号")
    isActive = Column(Integer, comment="激活状态", server_default="1")

    # 直接使用整数列，不设置外键约束
    role_id = Column(Integer, comment="角色ID")

    def to_dict(self):
        # 获取对象映射
        data = {column.name: getattr(self, column.name) for column in self.__table__.columns}
        if type(data.get('create_at')) is datetime.datetime:
            data['create_at'] = data['create_at'].strftime("%Y-%m-%d %H:%M:%S")
            data['update_at'] = data['update_at'].strftime("%Y-%m-%d %H:%M:%S")

        # 直接查询角色和权限
        role = None
        menu_list = []
        data['userPwd'] = "******"
        
        # 如果需要角色和菜单，可以在需要的地方手动查询
        return data


class Role(Base, BaseModel):
    __tablename__ = 'roles'

    id = Column(Integer, primary_key=True)
    name = Column(String(50))


class Permission(Base, BaseModel):
    __tablename__ = 'permissions'

    id = Column(Integer, primary_key=True)
    content = Column(Text)
    # 直接使用整数列，不设置外键约束
    role_id = Column(Integer, comment="角色ID")


class Logs(Base, BaseModel):
    __tablename__ = "logs"

    id = Column(Integer, primary_key=True, index=True)
    user = Column(String(255), comment="")
    api = Column(String(255), comment="")
    method = Column(String(10), comment="")
    params = Column(Text, comment="")
    status_code = Column(String(255), comment="")
    action = Column(String(255), comment="密码")
    ip = Column(String(32), comment="操作IP")
    response_time = Column(String(255), comment="响应时间")

    class Config:
        orm_mode = True

    @staticmethod
    def create(obj_in, db: Session = None):
        """ 添加对象 """
        close_session = False
        if db is None:
            db = next(get_db())
            close_session = True
            
        try:
            if obj_in:
                obj_in_data = jsonable_encoder(obj_in)
                db_obj = Logs(**obj_in_data)  # type: ignore
                db.add(db_obj)
                db.commit()
                return db_obj
        finally:
            if close_session:
                db.close()
